import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP
# SO_REUSEADDR设置1 允许在停止并重新启动程序后重用端口号。避免address already in use错误，否则得等一会操作系统才能取消绑定此端口
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 8000))
sock.listen()
#使用Windows下的telnet工具连接此服务端 打开侧边Terminal中的Local line editing设为Force on
connections = [] #记录多个连接
try:
    while True:
        conn, addr = sock.accept()
        connections.append(conn)
        print(f"I get a connection from {addr}")
        for c in connections:
            buffer = b""
            while buffer[-2:] != b"\r\n": #目前的处理方式 只能在第一个连接发送第一个带回车换行符的消息后，第二个连接才能连接上
                data = c.recv(2)
                if not data:
                    break
                else:
                    print(f"I got data: {data}")
                    buffer = buffer + data
            print(f"All the data is : {buffer}")
            c.sendall(buffer)
finally:
    sock.close()
